package com.hadoop.interceptor.util;


import com.hadoop.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HttpServletRequestUtils的工具类
 * Created by zzb on 15/12/2.
 */
public class HttpServletRequestUtils {
    /**判断是不是ajax的请求*/
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        String ajaxHeader = request.getHeader("Accept");
        if (StringUtils.containsIgnoreCase(ajaxHeader, "application/json")
                || StringUtils.containsIgnoreCase(ajaxHeader, "text/plain")
                || StringUtils.endsWith(requestUri, ".json")) {
            return true;
        }
        return false;
    }

    /**重定向*/
    public static void redirectUrl(HttpServletRequest request, HttpServletResponse response, String URL, String errmsg) {
        String ref = request.getRequestURI();
        String[] ignUrls = {"/user/receive/count","/api/bargain/trade/time"}; //忽略接收信息的URL
        for(String url : ignUrls){
            if (url.equals(ref)) {
                return;
            }
        }
        WebUtils.setSessionAttribute(request, Constants.COOKIE_KEY_WEB_HADOOP, ref);
        if (HttpServletRequestUtils.isAjaxRequest(request)) {
            try {
                response.setContentType("text/plain; charset=utf-8");
                response.getWriter().write("{\"retCode\":\"FAIL\",\"status\" : \"403\", \"msg\" : \""+errmsg+"\"}");
                response.getWriter().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                String path = request.getContextPath();
                String basePath = request.getScheme()+"://"+request.getServerName();
                if(request.getServerPort() != 80){
                    basePath = basePath+":"+request.getServerPort();
                }
                basePath = basePath+path;
                response.sendRedirect(basePath + URL + "?errmsg=" + java.net.URLEncoder.encode(errmsg, "UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
